<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="dialog"
    title="导入"
    width="450px"
    :close-on-click-modal="false"
    append-to-body
    @close="cancel"
  >
    <div>
      <el-form ref="editForm" :model="entity" :rules="rules" label-width="auto" :inline="true" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="档期:" prop="scheduleSubject">
              <el-input v-model="entity.scheduleSubject" size="mini" disabled style="width: 280px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="采购ID:" prop="buyerId">
              <el-select v-model="entity.buyerId" size="mini" style="width: 280px;">
                <el-option v-for="bid in parent.buyerIds" :key="bid" :label="bid" :value="bid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="清单文件:" required prop="fileList">
              <el-upload
                ref="upload"
                accept=".xlsx"
                :auto-upload="false"
                :on-exceed="handleExceed"
                :on-change="handleOnChange"
                :limit="1"
                :multiple="false"
                :file-list="entity.fileList"
                action="#"
              >
                <el-button size="mini" round type="primary">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且大小不超过64MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" size="mini" round @click="cancel">取消</el-button>
      <el-button type="primary" size="mini" round @click="doSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import request from '@/utils/request'
const tipMsg = '不能为空'
export default {
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      entity: this.emptyEntity(),
      rules: {
        buyerId: [{ required: true, message: tipMsg, trigger: 'blur' }, { required: true, message: tipMsg, trigger: 'change' }],
        fileList: [
          { validator: this.fileListCheck, trigger: 'blur' },
          { validator: this.fileListCheck, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    emptyEntity() {
      return {
        buyerId: '',
        fileList: [],
        scheduleId: null,
        scheduleSubject: null
      }
    },
    cancel() {
      this.dialog = false
      this.entity = this.emptyEntity()
    },
    fileListCheck(rule, value, callback) {
      if (this.entity.fileList == null || this.entity.fileList.length <= 0) {
        return callback(new Error('请选择上传Excel'))
      }
      return callback()
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      Message({
        message: '文件上传数量限制为1个。',
        type: 'warning',
        duration: 3 * 1000
      })
    },
    // 文件变动的钩子
    handleOnChange(file, fileList) {
      if (!(file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
        Message({
          message: '请上传格式为xlsx的文件。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      }
      var size = file.size / 1024 / 1024
      if (size > 64) {
        Message({
          message: '文件大小必须小于64M。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      } else {
        this.entity.fileList = fileList
      }
    },
    // 确定按钮触发
    doSubmit() {
      this.$refs.editForm.validate(valid => {
        var _this = this
        if (valid) {
          this.$confirm('确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.loading = true
            const file = this.entity.fileList[0]
            var formData = new FormData()
            formData.append('file', file.raw)
            formData.append('buyerId', this.entity.buyerId)
            formData.append('scheduleId', this.entity.scheduleId)
            request({
              method: 'put',
              url: '/olm-excel/excel/importOlmListData',
              data: formData,
              timeout: 600000,
              responseType: 'blob' // 指定获取数据的类型为blob
            }).then(
              function(response) {
                console.log(response)
                if (response.type === 'application/json') {
                  const reader = new FileReader()
                  reader.readAsText(response)
                  reader.onload = function(event) {
                    const msg = JSON.parse(reader.result) // 此处的msg就是后端返回的msg内容
                    if (!msg || msg === '') {
                      Message({
                        message: '导入成功',
                        type: 'success',
                        duration: 3 * 1000
                      })
                      _this.parent.toQuery()
                    } else if (msg.code === '-500') {
                      console.log(msg.result)
                      Message({
                        message: msg.result,
                        type: 'error',
                        duration: 3 * 1000
                      })
                    } else if (msg.code === '-1') {
                      Message({
                        message: '系统错误!',
                        type: 'error',
                        duration: 3 * 1000
                      })
                    }
                  }
                } else {
                  // console.log('response:' + response)
                  // 创建a标签并点击， 即触发下载
                  const url = window.URL.createObjectURL(response)
                  const link = document.createElement('a')
                  link.style.display = 'none'
                  link.href = url
                  link.setAttribute('download', '无法导入数据清单.xlsx')
                  document.body.appendChild(link)
                  link.click()
                  URL.revokeObjectURL(link.href) // 释放URL 对象
                  document.body.removeChild(link)
                }
              }
            ).catch(function(err) {
              console.log(err)
            })
            this.loading = false
            this.dialog = false
            this.entity.fileList.pop()
          })
        }
      })
    }
  }
}
</script>
